<?php
/** 
*图像处理类 
* 
*
* @author      john<john@morefun.me> 
* @version     $Id$ 
* @since        1.0 
*/  
class Services_Image{
	
	public function __construct()
	{
		

	}
	/** 
	* 获取图片宽度,高度  
	* 
	* 
	* @access public 
	* @param string $filename 图片路径
	* @return array 
	*/ 
	function getImageSize($filename)
	{

		$image = getimagesize($filename);
		list($width, $height) = $image;
		$result['width'] = $width;
		$result['height'] = $height;
		return $result;
	}
	
	
	/** 
	* 图片缩放  
	* 
	* 
	* @access public 
	* @param string $filename 原始图地址
	* @param string $newfilename 新图地址 path/subpath/filename
	* @param string $newwidth 缩放宽度 高度等比例缩放
	* @return bool  
	*/ 
	public function resizeImage($filename, $newfilename , $newwidth)
	{
		
		list($width, $height) = getimagesize($filename);
		$newheight = round($newwidth * $height / $width);
		$thumb = imagecreatetruecolor($newwidth, $newheight);
		
		$type = strtolower(substr(strrchr($filename,"."),1));
		$newfilename = $newfilename;
		if($type == 'jpeg' || $type == 'jpg')
		{
			$source = imagecreatefromjpeg($filename);
			$thumbRresult = imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			$result = imagejpeg($thumb, $newfilename,100);
		}
		elseif($type == 'gif')
		{
			$source = imagecreatefromgif($filename);
			$thumbRresult = imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			$result = imagegif($thumb, $newfilename,100);
			
		}
		elseif($type == 'bmp')
		{
			$source = imagecreatefromwbmp($filename);
			$thumbRresult = imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			$result = imagewbmp($thumb, $newfilename,100);			
		}
		elseif($type == 'png')
		{
			$source = imagecreatefrompng($filename);
			$thumbRresult = imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			$result = imagepng($thumb, $newfilename,100);
			
		}
		imagedestroy($thumb);
		imagedestroy($source);
		imagedestroy($thumbRresult);
		return array('result'=>$result,'type'=>$type);
	}
	
	/** 
	* 将远程的图片存到本地  
	* 
	* 
	* @access public 
	* @param string $filename 原始图地址
	* @return bool  
	*/ 
	public function saveRemoteImage($filename,$newfilename)
	{
		
		//$fetchService = Alibaba::Fetchurl();
		//$fetchGetTBResult = $fetchService->fetchByGet($filename);
		$type = strtolower(substr(strrchr($filename,"."),1));
		$fetchGetTBResult = $this->disguise_curl($filename);
		//$newfilename = $newfilename.'.'.$type;
		$result = file_put_contents($newfilename, $fetchGetTBResult);
		return array('result'=>$result,'type'=>$type);
	}

	/** 
	* 图片合层  
	* 
	* 
	* @access public 
	* @param string $sourcefile 原始图地址
	* @param string $watermarkfile 原始图地址
	* @param string $newfilename 合成图片的名称
	* @return bool  
	*/ 
	public function mergerImage($sourcefile, $watermarkfile,$newfilename)
	{
		#
		# $sourcefile = Filename of the picture to be watermarked.
		# $watermarkfile = Filename of the 24-bit PNG watermark file.
		#
		list($width, $height) = getimagesize($sourcefile);
		
		//Get the resource ids of the pictures
		$watermarkfile_id = imagecreatefrompng($watermarkfile);
		
		imageAlphaBlending($watermarkfile_id, false);
		imageSaveAlpha($watermarkfile_id, true);

		$fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));
		$newfilename = $newfilename.'.'.$fileType;
		
		switch($fileType) {
			case('gif'):
				$sourcefile_id = imagecreatefromgif($sourcefile);
				break;
				
			case('png'):
				$sourcefile_id = imagecreatefrompng($sourcefile);
				break;
				
			default:
				$sourcefile_id = imagecreatefromjpeg($sourcefile);
		}

		//Get the sizes of both pix   
	  $sourcefile_width=imageSX($sourcefile_id);
	  $sourcefile_height=imageSY($sourcefile_id);
	  $watermarkfile_width=imageSX($watermarkfile_id);
	  $watermarkfile_height=imageSY($watermarkfile_id);

		
		// if a gif, we have to upsample it to a truecolor image
		if($fileType == 'gif') {
			// create an empty truecolor container
			$tempimage = imagecreatetruecolor($sourcefile_width,$sourcefile_height);
			
			// copy the 8-bit gif into the truecolor image
			imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0, $sourcefile_width, $sourcefile_height);
			
			// copy the source_id int
			$sourcefile_id = $tempimage;
		}

		imagecopy($sourcefile_id, $watermarkfile_id, 0, $height-150, 0, 0, $watermarkfile_width, $watermarkfile_height);

		//Create a jpeg out of the modified picture
		switch($fileType) {
		
			// remember we don't need gif any more, so we use only png or jpeg.
			// See the upsaple code immediately above to see how we handle gifs
			case('png'):
				//header("Content-type: image/png");
				$result = imagepng ($sourcefile_id, $newfilename);
				break;
				
			default:
				//header("Content-type: image/jpg");
			   $result = imagejpeg($sourcefile_id,$newfilename);
		}           
	  
		imagedestroy($sourcefile_id);
		imagedestroy($watermarkfile_id);
		return array('result'=>$result,'type'=>$fileType);
    
	}
	/*
	save to cdn
	*/
	public function saveToCdn($filename)
	{
		/*
		check folder
		*/
		$path = $this->checkFolder();
		$picService = $PicServiceFactory->getPicService();
		//$content = $this->disguise_curl('http://'.$_SERVER['SERVER_NAME'].$filename);
		$content = file_get_contents($filename, true);
		$response = $picService->savePic($path,'',$content);
		//$result=$response->getResult();		
			if($response->isSuccess())
			{
				$result=$response->getResult();		
				return $result->fullUrl;
			}
			else
			{
				return $response->getErrorMsg();
			}
	}
	/*
	delete pic files
	@params array pic lists
	*/
	public function deletePics($files)
	{
		
		if(is_array($files))
		{
			foreach($files as $k=>$v)
			{
				unlink($v);
			}
		}
		else
		{
			 unlink($files);
		}
		return true;
	}
	/*
	check image format
	*/
	public function checkIfImage($filename)
	{
		$fileType = strtolower(substr($filename, strlen($filename)-3));
		if($fileType =='jpg' || $fileType =='png' || $fileType =='gif')
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
	
	/*
	create folder
	*/
	public function checkFolder()
	{
		$today = date('Ymd');
		//echo $today;
		$picService = $PicServiceFactory->getPicService();
		//$response=$picService->createDir($today);
		$response = $picService->isDirExist($today);	
		//$response=$picService->deleteDir($today);
		//$response=$picService->createDir($today);
		if($response->isSuccess())
		{
			return $today;
			
		}
		else
		{
			$response = $picService->createDir($today);
			if($response->isSuccess())
			{
				return $today;
			}
			else
			{
				return '';
			}
		}
		
	}
	
	
	/** 
	* curl远程的图片或者html文件
	* 
	* 
	* @access public 
	* @param string $url
	* @return string cotent  
	*/ 	
	
	public function disguise_curl($url, $proxy=null) 
    { 
        $curl = curl_init();

        // Setup headers - I used the same headers from Firefox version 2.0.0.6 
        // below was split up because php.net said the line was too long. :/ 
        $header = array();
        $header[0]  = "Accept: text/xml,application/xml,application/xhtml+xml,"; 
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
        $header[] = "Cache-Control: max-age=0"; 
        $header[] = "Connection: keep-alive"; 
        $header[] = "Keep-Alive: 300"; 
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; 
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Cookie: cna=l+pgC/cDdWcCAWVF+/5q+UVs; miid=3317872020099775032; __utma=6906807.434603219.1390489590.1390489590.1390489590.1; __utmz=6906807.1390489590.1.1.utmcsr=fuwu.taobao.com|utmccn=(referral)|utmcmd=referral|utmcct=/ser/detail.htm; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0%26__ll%3D-1%26_ato%3D0; lzstat_uv=24182050841715729711|2581762@3201199@2945730@2948565@2798379@2043323@3045821@2805963@2738597@878758@2208862@3027305@3284827@2581759@2581747@2938535@2938538@2879138@3010391; ali_ab=60.186.203.48.1390489531936.4; l=asd890241::1397182032328::11; v=0; uc3=nk2=AmJam4TqFyWJ&id2=W8ncTY3m5dw%3D&vt3=F8dATHtpuP76kDFmmBg%3D&lg2=V32FPkk%2Fw0dUvg%3D%3D; existShop=MTM5NzYxMTM1NA%3D%3D; lgc=asd890241; tracknick=asd890241; sg=10d; cookie2=6b8940c7741e940084cc149db11f8b7c; mt=cp=0&np=&ci=1_1&cyk=0_0; cookie1=B0EwsR%2FpnjjSjqpUTsxO8woKrOXzJMXtv9vP4SUJA5I%3D; unb=80893640; t=43525df761cffb84c1297592f666dd75; publishItemObj=Ng%3D%3D; _cc_=UIHiLt3xSw%3D%3D; tg=0; _l_g_=Ug%3D%3D; _nk_=asd890241; cookie17=W8ncTY3m5dw%3D; pnm_cku822=117fCJmZk4PGRVHHxtNZngkZ3k%2BaC52PmgTKQ%3D%3D%7CfyJ6Zyd9OGcmY3YkZHYibx4%3D%7CfiB4D15%2BZH9geTp%2FJyN8PDJtLBMbCF4lHw%3D%3D%7CeSRiYjNhIHA3dWI0c2A4eGwmfz16PnhrNHJlMH1kJnc8bS1hfzoT%7CeCVoaEATTRBWFx1IEBRReHZYZg%3D%3D%7CeyR8C0obRRhYABdDABNTFAFGEU8XUxMFTgMVSREMSxxeG1MWCTMa%7CeiJmeiV2KHMvangudmM6eXk%2BAA%3D%3D; _tb_token_=3ee5e3b8e7690; uc1=lltime=1397569800&cookie14=UoLVYuvN1ebuMw%3D%3D&existShop=true&cookie16=Vq8l%2BKCLySLZMFWHxqs8fwqnEw%3D%3D&cym=1&cookie21=URm48syIZJTgtchfymSXVA%3D%3D&tag=3&cookie15=VFC%2FuZ9ayeYq2g%3D%3D";
        $header[] = "Pragma: "; // browsers keep this blank. 

        if (!is_null($proxy)) {
            curl_setopt ($curl, CURLOPT_PROXY, $proxy); 
        }

        curl_setopt($curl, CURLOPT_URL, $url); 
        curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)'); 
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com'); 
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate'); 
        curl_setopt($curl, CURLOPT_AUTOREFERER, true); 
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);

        $html = curl_exec($curl); // execute the curl command 
        curl_close($curl); // close the connection 

        return $html; // and finally, return $html 
    }
	
	/*
	将base64的图像传到图片空间
	$params['base64']
	$params['shopId']
	$params['pageId']
	*/
	public function base64ToCdn($params)
	{
		$util = new Services_Utility();
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $params['base64'], $result)){
			$type = $result[2];
			$screen = dirname(__FILE__)."/../screenshot/".$params['shopId'].'_'.$params['pageId'].".{$type}";
			if (file_put_contents($screen, base64_decode(str_replace($result[1], '', $params['base64'])))){
				$cid = $util->getUploadDir();
				$param = array(
					'cid' => $cid,
					'img' => '@'.$screen,
					'inputtitle' => $params['shopId'].'_'.$params['pageId']
				);
				$pic = $util->uploadPicture($param);
				if($pic['picture_upload_response'])
				{
					$screenshot = $pic['picture_upload_response']['picture']['picture_path'];
					unlink($screen);//移除本地图片
					return $screenshot;
					
				}
				else
				{
					$appLog->warn('shopid:'.$shopId.' pageid:'.$id.json_encode($pic));
					return false;
				}
				
			}
			else
			{
				
				//TODO default screenshot image
				return true;
			}
		 
		}
	
		
		
	}
	
}
?>